<template>
  <div class="knowledge-app">
    <el-tabs v-model="activeTab">
      <!-- 知识检索 -->
      <el-tab-pane label="知识检索" name="search">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="请输入关键词检索（如“车床主轴振动”）"
            clearable
            @input="handleSearch"
            style="width: 300px; margin-right: 16px;"
          />
          <el-select
            v-model="filterModel"
            placeholder="设备型号"
            clearable
            @change="handleSearch"
            style="width: 150px; margin-right: 16px;"
          >
            <el-option
              v-for="item in modelOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
          <el-select
            v-model="filterFaultType"
            placeholder="故障类型"
            clearable
            @change="handleSearch"
            style="width: 150px;"
          >
            <el-option
              v-for="item in faultTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </div>
        <el-table
          :data="searchResults"
          style="width: 100%; margin-top: 20px;"
          v-loading="loading"
          empty-text="暂无数据"
        >
          <el-table-column prop="title" label="案例名称" />
          <el-table-column prop="model" label="设备型号" width="120" />
          <el-table-column prop="faultType" label="故障类型" width="120" />
          <el-table-column prop="relevance" label="相关性" width="100">
            <template slot-scope="scope">
              {{ scope.row.relevance }}%
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <template slot-scope="scope">
              <el-button type="text" @click="viewCase(scope.row)">查看</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 案例详情弹窗 -->
        <el-dialog
          :visible.sync="caseDialogVisible"
          width="600px"
          :title="selectedCase ? selectedCase.title : '案例详情'"
        >
          <div v-if="selectedCase">
            <p><b>设备型号：</b>{{ selectedCase.model }}</p>
            <p><b>故障类型：</b>{{ selectedCase.faultType }}</p>
            <p><b>相关性：</b>{{ selectedCase.relevance }}%</p>
            <p><b>维修流程：</b></p>
            <el-steps direction="vertical" :active="selectedCase.process.length">
              <el-step
                v-for="(step, idx) in selectedCase.process"
                :key="idx"
                :title="step"
              />
            </el-steps>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="caseDialogVisible = false">关闭</el-button>
          </span>
        </el-dialog>
      </el-tab-pane>

      <!-- 故障诊断 -->
      <el-tab-pane label="故障诊断" name="diagnosis">
        <div class="diagnosis-section">
          <el-alert
            title="系统已为您推荐以下相似案例"
            type="info"
            show-icon
            style="margin-bottom: 16px;"
          />
          <el-card
            v-for="item in recommendedCases"
            :key="item.id"
            style="margin-bottom: 16px;"
          >
            <div>
              <b>相似度{{ item.similarity }}%的案例：</b>
              {{ item.title }}（{{ item.date }}，{{ item.model }}，{{ item.faultType }}）
            </div>
            <div style="margin: 8px 0;">
              <b>维修策略：</b>{{ item.strategy }}
            </div>
            <el-button
              type="primary"
              size="mini"
              @click="useStrategy(item)"
              :disabled="usedStrategyId === item.id"
            >
              一键引用维修策略
            </el-button>
            <span v-if="usedStrategyId === item.id" style="color: #67c23a; margin-left: 8px;">已引用</span>
          </el-card>
          <el-alert
            v-if="usedStrategy"
            :title="'已引用维修策略：' + usedStrategy"
            type="success"
            show-icon
            style="margin-top: 16px;"
          />
        </div>
      </el-tab-pane>

      <!-- 知识分享 -->
      <el-tab-pane label="知识分享" name="share">
        <div class="share-section">
          <el-select
            v-model="shareCaseId"
            placeholder="请选择要分享的案例"
            style="width: 300px; margin-bottom: 16px;"
          >
            <el-option
              v-for="item in allCases"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
          <el-button
            type="primary"
            :disabled="!shareCaseId"
            @click="generateShareLink"
          >生成分享链接</el-button>
          <div v-if="shareLink" style="margin-top: 16px;">
            <el-input
              v-model="shareLink"
              readonly
              style="width: 400px;"
              size="small"
            />
            <el-button
              type="success"
              size="small"
              style="margin-left: 8px;"
              @click="copyShareLink"
            >复制链接</el-button>
            <span v-if="copySuccess" style="color: #67c23a; margin-left: 8px;">已复制！</span>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import { Message } from 'element-ui';

const MOCK_CASES = [
  {
    id: 1,
    title: '车床主轴振动故障维修案例',
    model: 'CA6140',
    faultType: '机械故障',
    relevance: 98,
    process: [
      '初步检查主轴部件',
      '检测轴承磨损情况',
      '更换损坏轴承',
      '重新校准主轴',
      '试运行并监测振动',
    ],
    strategy: '更换主轴轴承并校准主轴',
    date: '2024-10-12',
  },
  {
    id: 2,
    title: '数控车床电气故障处理',
    model: 'CK6136',
    faultType: '电气故障',
    relevance: 85,
    process: [
      '检查电源线路',
      '检测控制系统',
      '更换损坏电气元件',
      '恢复系统设置',
    ],
    strategy: '更换损坏电气元件并恢复设置',
    date: '2024-09-20',
  },
  {
    id: 3,
    title: 'CA6140主轴异响案例',
    model: 'CA6140',
    faultType: '机械故障',
    relevance: 92,
    process: [
      '检查主轴润滑情况',
      '清理主轴腔体',
      '更换润滑油',
      '测试运行',
    ],
    strategy: '清理主轴腔体并更换润滑油',
    date: '2024-10-05',
  },
  {
    id: 4,
    title: '立式车床液压系统故障',
    model: 'C5116',
    faultType: '液压故障',
    relevance: 80,
    process: [
      '检查液压油位',
      '检测液压泵压力',
      '更换液压滤芯',
      '排除系统空气',
    ],
    strategy: '更换液压滤芯并排除空气',
    date: '2024-08-15',
  },
];

const STORAGE_KEY = 'knowledge_cases';

export default {
  name: 'KnowledgeRetrievalAndApplication',
  data() {
    return {
      activeTab: 'search',
      searchKeyword: '',
      filterModel: '',
      filterFaultType: '',
      loading: false,
      searchResults: [],
      caseDialogVisible: false,
      selectedCase: null,
      usedStrategy: '',
      usedStrategyId: null,
      recommendedCases: [],
      shareCaseId: null,
      shareLink: '',
      copySuccess: false,
      allCases: [],
    };
  },
  computed: {
    modelOptions() {
      return [...new Set(this.allCases.map(c => c.model))];
    },
    faultTypeOptions() {
      return [...new Set(this.allCases.map(c => c.faultType))];
    },
  },
  created() {
    this.initCases();
    this.handleSearch();
    this.initRecommendedCases();
  },
  methods: {
    // 初始化案例数据
    initCases() {
      const local = localStorage.getItem(STORAGE_KEY);
      if (local) {
        this.allCases = JSON.parse(local);
      } else {
        this.allCases = MOCK_CASES;
        localStorage.setItem(STORAGE_KEY, JSON.stringify(MOCK_CASES));
      }
    },
    // 检索逻辑
    handleSearch() {
      this.loading = true;
      setTimeout(() => {
        let results = this.allCases.map(c => ({
          ...c,
          relevance: this.calcRelevance(c, this.searchKeyword),
        }));
        // 过滤
        if (this.filterModel) {
          results = results.filter(c => c.model === this.filterModel);
        }
        if (this.filterFaultType) {
          results = results.filter(c => c.faultType === this.filterFaultType);
        }
        // 相关性排序
        results = results
          .filter(c => c.relevance > 0)
          .sort((a, b) => b.relevance - a.relevance);
        this.searchResults = results;
        this.loading = false;
      }, 300);
    },
    // 相关性计算（简单关键词匹配+标题/流程/策略）
    calcRelevance(caseItem, keyword) {
      if (!keyword) return 100;
      const kw = keyword.trim().toLowerCase();
      let score = 0;
      if (caseItem.title.toLowerCase().includes(kw)) score += 60;
      if (caseItem.process.some(step => step.toLowerCase().includes(kw))) score += 20;
      if (caseItem.strategy.toLowerCase().includes(kw)) score += 10;
      if (caseItem.faultType.toLowerCase().includes(kw)) score += 5;
      if (caseItem.model.toLowerCase().includes(kw)) score += 5;
      return Math.min(score, 100);
    },
    // 查看案例详情
    viewCase(row) {
      this.selectedCase = row;
      this.caseDialogVisible = true;
    },
    // 推荐相似案例
    initRecommendedCases() {
      // 取与第一个案例同型号同故障的案例作为推荐
      const base = this.allCases[0];
      this.recommendedCases = this.allCases
        .filter(
          c =>
            c.id !== base.id &&
            c.model === base.model &&
            c.faultType === base.faultType
        )
        .map(c => ({
          ...c,
          similarity: 92,
        }));
      // 若无同型号同故障，则推荐相关性最高的两个
      if (this.recommendedCases.length === 0) {
        this.recommendedCases = this.allCases
          .filter(c => c.id !== base.id)
          .sort((a, b) => b.relevance - a.relevance)
          .slice(0, 2)
          .map(c => ({
            ...c,
            similarity: 85,
          }));
      }
    },
    // 一键引用维修策略
    useStrategy(item) {
      this.usedStrategy = item.strategy;
      this.usedStrategyId = item.id;
      Message.success('维修策略已引用！');
    },
    // 生成分享链接
    generateShareLink() {
      if (!this.shareCaseId) return;
      // 这里用 base64 编码模拟生成链接
      const caseData = this.allCases.find(c => c.id === this.shareCaseId);
      const dataStr = btoa(encodeURIComponent(JSON.stringify(caseData)));
      this.shareLink = `${window.location.origin}/share/case?data=${dataStr}`;
      this.copySuccess = false;
    },
    // 复制分享链接
    copyShareLink() {
      if (!this.shareLink) return;
      const input = document.createElement('input');
      input.value = this.shareLink;
      document.body.appendChild(input);
      input.select();
      document.execCommand('copy');
      document.body.removeChild(input);
      this.copySuccess = true;
    },
  },
  watch: {
    activeTab(val) {
      if (val === 'diagnosis') {
        this.initRecommendedCases();
      }
    },
  },
};
</script>

<style scoped>
.knowledge-app {
  padding: 24px;
  background: #fff;
  min-height: 100vh;
}
.search-bar {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.diagnosis-section {
  max-width: 600px;
  margin: 0 auto;
}
.share-section {
  max-width: 600px;
  margin: 0 auto;
  padding-top: 40px;
}
</style>
